﻿using B.S.Outsourcing.Domain;
using B.S.Outsourcing.ErrorCode;
using B.S.Outsourcing.Infatructrue;
using B.S.Outsourcing.Read.Api.Application.Command.OutSourOrderModel;
using MediatR;

namespace B.S.Outsourcing.Read.Api.Application.CommandHandler.OutSourOrderModel
{
    public class QueryOutsourOrderCommandHandler : IRequestHandler<QueryOutsourOrderCommand, ApiPaging<OutsourcingOrderModel>>
    {
        private readonly IBaseRepository<OutsourcingOrderModel> baseRepository;
        private readonly DBHelper1 dBHelper;

        public QueryOutsourOrderCommandHandler(IBaseRepository<OutsourcingOrderModel> baseRepository, DBHelper1 dBHelper)
        {
            this.baseRepository = baseRepository;
            this.dBHelper = dBHelper;
        }

        public async Task<ApiPaging<OutsourcingOrderModel>> Handle(QueryOutsourOrderCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<OutsourcingOrderModel> result = new ApiPaging<OutsourcingOrderModel>();
            var sql = $"select * from OutsourcingOrderModel where IsDelete=0";
            if (!string.IsNullOrEmpty(request.DocumentCode))
            {
                sql += $"and DocumentCode like '%{request.DocumentCode}%'";
            }
            if (!string.IsNullOrEmpty(request.DocumentStatus))
            {
                sql += $"and DocumentStatus='{request.DocumentStatus}'";
            }
            if (!string.IsNullOrEmpty(request.BusinessStatus))
            {
                sql += $"and BusinessStatus='{request.BusinessStatus}'";
            }
            if (request.BeginData!=null)
            {
                sql += $"and CreatedDate>='{request.BeginData}'";
            }
            if (request.EndData!=null)
            {
                sql += $"and CreatedDate<='{request.EndData}'";
            }
            var model = $"{sql} order by OutsourcingOrderModel.Id offset(({request.pageindex - 1})*{request.pagesize}) rows fetch next {request.pagesize} rows only";
            result.list = dBHelper.GetList<OutsourcingOrderModel>(model);
            result.Totalcount = result.list.Count();
            result.Totalpage = (int)Math.Ceiling(result.Totalcount * 1.0 / request.pagesize);
            result.Code = ApiEnums.成功;
            result.Message = "成功";
            return await Task.FromResult(result);
        }
    }
}
